﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ProgNetComponents.NamedObjects
{
    public class NamedCollectionBase<T> : CollectionBase where T : class, INamedObject 
    {
        protected virtual bool AllowDuplicates
        {
            get { return false; }
        }
        public void Add(T item)
        {
            if (item != null)
            {
                if (!Contains(item.Name) || AllowDuplicates)
                {
                    List.Add(item);
                }
            }
        }
        
        public T this[string name]
        {
            get
            {
                foreach (T  item in List)
                    if (item.Name == name)
                        return item;
                return null;
            }
        }
        public T this[int i]
        {
            get { return List[i] as T; }
        }
        
        public bool Contains(string name)
        {
            if (name == null)
                return false;
            return this[name] != null;
        }
        
        public void Remove(string name)
        {
            T item = this[name];
            while (item != null)
            {
                List.Remove(item);
                item = this[name];
            }
        }
        public void Remove(T item)
        {
            if (List.Contains(item))
                List.Remove(item);
        }
    }
}
